package com.lanou.bbs.dao;

import com.lanou.bbs.entity.User;
import com.lanou.bbs.utils.JDBCUtils;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class UserDao {
    public User findByUsername(String username) throws SQLException {
        Connection connection = JDBCUtils.getConnection();

        String sql = "select * from user where username=?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, username);
        ResultSet rs = ps.executeQuery();

        if (rs.next()) {
            User user = new User();
            user.setUserId(rs.getInt("user_id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setHead(rs.getString("head"));
            user.setGender(rs.getString("gender"));
            user.setRegTime(rs.getDate("reg_time"));

            connection.close();
            return user;
        } else {
            connection.close();
            return null;
        }
    }

    public void add(User user) throws SQLException {

        Connection connection = JDBCUtils.getConnection();

        String sql = "insert into user(username,password,head,reg_time,gender) values (?,?,?,?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, user.getUsername());
        ps.setString(2, user.getPassword());
        ps.setString(3, user.getHead());
        ps.setDate(4, null);
        ps.setString(5, user.getGender());

        ps.executeUpdate();

        connection.close();
    }
}
